package com.example.pharmacy.controller;

import com.example.pharmacy.commen.Constant;
import com.example.pharmacy.model.Result;
import com.example.pharmacy.model.UserInfo;
import com.example.pharmacy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: asus
 * Date: 2024-12-21
 * Time: 16:03
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String userName, String password, HttpSession session) {
        if (userName == null || password == null) {
            return Result.fail("用户名或密码为空");
        }
        UserInfo userInfo = userService.selectUserByName(userName);
        if (userInfo == null) {
            return Result.fail("用户名不存在");
        }
        if (!password.equals(userInfo.getPassword())) {
            return Result.fail("密码错误");
        }
        session.setAttribute(Constant.SESSION_USER_KEY, userName);
        return Result.success(true);
    }
    @RequestMapping(value = "/register", produces = "application/json")
    public Result register(String userName, String password, String pswConfirm) {
        if (userName == null || password == null || pswConfirm == null) {
            return Result.fail("");
        }
        if (!pswConfirm.equals(password)) {
            return Result.fail("两次输入的密码不一致");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        userInfo.setPassword(password);
        Integer result = userService.insertUserInfo(userInfo);
        if (result <= 0) {
            return Result.fail("用户名重复, 请重新注册");
        }
        return Result.success("");
    }
    @RequestMapping("/exit")
    public Result exit(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute(Constant.SESSION_USER_KEY);
        return Result.success("");
    }
}
